package com.wenhuitec.android.tang.ui.activity;

import static java.lang.Thread.sleep;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.iot.sdk.utils.SystemUtils;
import com.dhkj.web.bean.OrderProductModel;
import com.dhkj.web.utils.MyObserverRes;
import com.dhkj.web.utils.RequestUtils;
import com.wenhuitec.android.tang.R;
import com.wenhuitec.android.tang.config.SystemInit;
import com.wenhuitec.android.tang.entity.DeviceCarModel;
import com.wenhuitec.android.tang.sysui.model.CarFoodsModel;
import com.wenhuitec.android.tang.ui.dialog.MsgDialog;
import com.wenhuitec.android.tang.util.BytesUtil;
import com.wenhuitec.android.tang.util.ScanKeyManager;
import com.wenhuitec.android.tang.util.UsbPrinter;
import com.wsm.hidlib.HIDManager;
import com.wsm.hidlib.callback.HIDDataListener;
import com.wsm.hidlib.callback.HIDOpenListener;
import com.wsm.hidlib.constant.ConnectCostant;
import com.wsm.hidlib.util.HexUtil;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

public class CardActivity extends AppCompatActivity {

    private Context mContext;
    private ScanKeyManager scanKeyManager;
    private String orders = "";
    private UsbPrinter usbPrinter;

    private Button cancelBut;
    private Button checkBut;
    private TextView priceTv;
    private TextView msgTv;
    private String price = "";

    List<DeviceCarModel> deviceCarModelList;

    public static void startAct(Context context, String json) {
        Intent intent = new Intent(context, CardActivity.class);
        intent.putExtra("data", json);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan_qr);
        mContext = this;
        Bundle extras = this.getIntent().getExtras();
        assert extras != null;
        String data = extras.getString("data");
        usbPrinter = UsbPrinter.getInstance(this);
        cancelBut = findViewById(R.id.cancel_button);
        priceTv = findViewById(R.id.priceTv);
        msgTv = findViewById(R.id.msgTv);
        msgTv.setText("请刷卡");
        deviceCarModelList = JSONArray.parseArray(data, DeviceCarModel.class);
        if (deviceCarModelList == null || deviceCarModelList.isEmpty() || deviceCarModelList.get(0).getCarFoods().isEmpty()) {
            finish();
            return;
        }
        cancelBut.setOnClickListener(v -> finish());
        checkBut = findViewById(R.id.check_button);
//        checkBut.setOnClickListener(view -> {
//            showInputPassword();
//        });

        BigDecimal price = new BigDecimal(0);
        for (DeviceCarModel goo : deviceCarModelList) {
            for (CarFoodsModel goo2 : goo.getCarFoods()) {
                price = price.add(new BigDecimal(goo2.getPrice()).multiply(new BigDecimal(goo2.getFoodNumber())));
            }
        }
        priceTv.setText(String.format("￥%s", price.stripTrailingZeros().setScale(2, RoundingMode.DOWN).toPlainString()));
        scanKeyManager = new ScanKeyManager((String value) -> {
            Log.i("CardActivity", "ScanValue->" + value);
            toCardPay(value);
        });
    }

    private int READ_OK = 1;

    private HIDOpenListener mHIDOpenListener;
    private HIDDataListener mHidDataListener;

    private void initHID() {
        HIDManager.getInstance().enableLog(true);
        HIDManager.getInstance().openHID(mContext, mHIDOpenListener, mHidDataListener);

    }

    private void initListener() {
        //回调数据有关页面展示的请在主线程进行。
        mHIDOpenListener = new HIDOpenListener() {
            @Override
            public void openSuccess(final int openSuccessStatus) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (openSuccessStatus == ConnectCostant.USB_CONNECT) {
                            System.out.println("连接USB");

                        } else if (openSuccessStatus == ConnectCostant.COMMUNICATION_OPEN) {
                            System.out.println("通讯建立");
                        }
                    }
                });

            }

            @Override
            public void openError(int openErrorStatus) {
                if (openErrorStatus == ConnectCostant.USB_DISCONNECT) {
                    //USB断开
                    System.out.println("断开USB");
                }
                if (openErrorStatus == ConnectCostant.COMMUNICATION_CLOSE) {
                    //服务销毁
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            System.out.println("通讯断开");
                        }
                    });

                }
            }

        };

        mHidDataListener = new HIDDataListener() {
            @Override
            public void onDataReceived(byte status, String dataMessage) {
                if (!TextUtils.isEmpty(dataMessage)) {
                    String result = dataMessage;
                    System.out.println("onDataReceived: length:" + dataMessage.length() + "   content:" + result);
                    Message message = Message.obtain();
                    message.what = READ_OK;
                    message.obj = result;
                    handler.sendMessage(message);
                }
            }

            @Override
            public void onOriginalDataReceived(byte status, byte[] bytes, int length) {
                String formatHexString = HexUtil.formatHexString(bytes);
                System.out.println("onOriginalDataReceived: " + formatHexString);
            }
        };
//        mHidSequenceNumberListener = new HIDSequenceNumberListener() {
//            @Override
//            public void onSequenceNumberReceived(byte[] bytes, int length) {
//
//                if (length > 0) {
//                    String formatChar = StringFormat.bytes2String(bytes, foramt);
//                    System.out.println("onSequenceNumberReceived: " + formatChar);
//                    Message message = Message.obtain();
//                    message.what = READ_OK;
//                    message.obj = formatChar;
//                    handler.sendMessage(message);
//                }
//            }
//        };

    }


    @Override
    protected void onResume() {
        super.onResume();
        initListener();
        initHID();
    }

    private long lastCard;
    private Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == READ_OK) {
                String data = (String) msg.obj;
                data = data.trim();
                toCardPay(data);
            }
        }
    };

    private void toCardPay(String cardSn) {
        if (System.currentTimeMillis() - lastCard > (5 * 1000)) {
            lastCard = System.currentTimeMillis();
        } else {
            Toast.makeText(mContext, "请勿重复刷卡", Toast.LENGTH_LONG).show();
            return;
        }
        deviceCarModelList.get(0).setCardsn(cardSn);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("auth", cardSn);
        jsonObject.put("cartModel", deviceCarModelList);
        jsonObject.put("dzkCodeType", SystemInit.getInstance(mContext).getDzkCodeType());
        System.out.println(jsonObject.toJSONString());
        RequestUtils.toDepotPrePayBatch(mContext, new MyObserverRes<JSONObject>(mContext) {
            @Override
            public void onSuccess(JSONObject result) {
                String msg = "支付成功\r\n" + "卡余额:" + result.getJSONObject("fk").getString("kye") + "\r\n 卡补贴余额：" + result.getJSONObject("fk").getString("btye");
                MsgDialog msgDialog = new MsgDialog();
                msgDialog.show(mContext, msg, new MsgDialog.OnBottomClickListener() {
                    @Override
                    public void positive() {
                        OrderProductModel orderProductModel = new OrderProductModel();
                        byte[] printByte = BytesUtil.printProductPay(orderProductModel, jsonObject, result);
                        if (printByte != null) {
                            try {
                                usbPrinter.write(printByte);
                            } catch (Exception e) {
                                Log.e("CardActivity", e.toString());
                            }
                        }
                        setResult(RESULT_OK);
                        finish();
                    }

                    @Override
                    public void negative() {

                    }
                });
            }

            @Override
            public void onFailure(Throwable e, String errorMsg) {
                msgTv.setText(errorMsg);
            }
        }, jsonObject.toJSONString(), cardSn);
    }

    @Override
    protected void onPause() {
        super.onPause();
        HIDManager.getInstance().closeHID();
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() != KeyEvent.KEYCODE_BACK) {
            scanKeyManager.analysisKeyEvent(event);
            return true;
        }
        return super.dispatchKeyEvent(event);
    }
}